# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : check_editor.py
# Date      : 2019/8/5 
# IDE       : PyCharm
# Version   : 1.1.1
# -------------------------------
# ----------- update ------------
# 1.1.1 : 优化操作逻辑，添加新检查项
# -------------------------------
import os
import traceback

import maya.cmds as mc
import maya.mel as mel

from configs.constants.global_constant import *

import scripts.commonCmds as con
reload(con)
import scripts.deformerCmds as dc
reload(dc)
import editors.editor as editor
reload(editor)

class CheckEditor(editor.Editor):
    def __init__(self):
        super(CheckEditor,self).__init__()
        self.except_info = {}
    def win(self):
        _win = self.selfWindow()
        mc.window(_win,e=True,wh=[400,320],)
        self.menu_layout()
        inlayout = mc.columnLayout(adj=True)

        self.main_layout()
        
        # mc.text(self.text("ddddd"))
        self.copyright(inlayout)
        mc.setParent("..")
        mc.showWindow(_win)
        return
    def menu_layout(self):
        mc.menuBarLayout(bgc=self.rgbConvert(118, 137, 143))
        mc.menu("File" )
        mc.menuItem("Log ...",c=lambda *args:self.progress_log())

        mc.menuItem("Config ...",subMenu=True)
        mc.radioMenuItemCollection()
        mc.menuItem("Common",radioButton=True)
        mc.setParent('..', menu=True)
        mc.setParent("..")
        
        return
    def main_layout(self):
        column = mc.columnLayout(adj=True)
        mc.separator()
    
        mc.optionMenuGrp("check_mode", l="Check Mode : ",bgc=self.rgbConvert(6,82,121))
        mc.menuItem("Rig")
        mc.menuItem("Model")
        mc.setParent("..")

        mc.separator()
        mlayout = mc.columnLayout("publish_check_list_layout", adj=True)
        
        mc.setParent("..")
    
        mc.separator()
        # row = mc.rowLayout(nc=10)
        # mc.button(" - Check - ", c=lambda *args: self.btn_checkAll(),bgc=self.rgbConvert(243,104,56),w=150)
        mc.button(" - Fix - ", c=lambda *args: self.btn_checkAll(),bgc=self.rgbConvert(243,104,56),w=150)

        # mc.setParent("..")
        mc.separator()
        mc.setParent("..")
        
        self.refresh_checklist()
        
        return
    
    def refresh_checklist(self):
    
        check_mode = mc.optionMenuGrp("check_mode", q=True, v=True)
        if check_mode == "Rig":
            clist = [
                "hide_locator",
                "hide_joint",
                "hide_ikhandle",
                "hide_deformer",
                "clear_namespace",
                "delete_nodeEditorInfo",
                "delete_unusedItems",
                 ]
    
        for cl in clist:
            self.checkRowlayout(cl)
        # print clist
        return

    def checkRowlayout(self, bname, ):

        mc.rowLayout(bname, nc=10, parent="publish_check_list_layout")
        
        cb = mc.checkBox(con.lname(bname,"cb"),l="",rs=True,v=True)

        b1 = mc.button(bname + "_btn", l=bname, c=lambda *args: self.btn_clickCmd(bname), w=260)

        t_icon = os.path.join(gIconPath, "none.png")
        itb = mc.iconTextButton(bname + "_itb", image=t_icon, w=25, h=25,)
        
        mc.setParent("..")
        return
    
    def btn_exceptInfo(self,bname):
        winName = bname+"_info"
        self.isExist(winName)
        _win = mc.window(winName,)
        mc.window(_win,e=True,wh=[250,250])
        
        mc.columnLayout(adj=True)
        mc.text(l=self.except_info[bname],ww=True)
        mc.showWindow(_win)
        
        return
    
    def btn_clickCmd(self, bname):
        
        try:
            self.btn_fix(bname)
            t_icon = os.path.join(gIconPath, "true.png")
            mc.iconTextButton(bname + "_itb", e=True, image=t_icon)
            self.except_info[bname] = "return 0"
        except Exception,e:
            ex = traceback.format_exc()
            self.except_info[bname] = ex
            t_icon = os.path.join(gIconPath, "false.png")
            mc.iconTextButton(bname + "_itb", e=True, image=t_icon,c=lambda *args:self.btn_exceptInfo(bname))
        
        finally:
            mc.progressWindow(endProgress=1)

        return
    def btn_checkAll(self):
    
        carray = mc.columnLayout("publish_check_list_layout", q=True, ca=True)
        
        for ca in carray:
            if mc.checkBox(ca+"_cb",q=True,v=True):
                # print ca
                self.btn_clickCmd(ca)
        return
    
    def btn_check(self,keyword):
        # clist = ["joint_drawStyle",
        #          "namespace",
        #          "skinCluter_unused_inf",
        #          "unused_node",
        #          "duplicate_name",
        #          "need_hide",
        #          ]
        if keyword == "joint_drawStyle":
            fjoints = list()
            for jot in mc.ls(type="joint", fl=True):
                drawStyle = mc.getAttr(jot + ".drawStyle")
                if drawStyle != 2:
                    fjoints.append(jot)
            return fjoints
        
        elif keyword == "namespace":
            return con.getNamespace()
        
        elif keyword == "skinCluter_unused_inf":
            skinNodes = mc.ls(type="skinCluster", fl=True)
            usns = list()
            for sn in skinNodes:
                usns.append(dc.skinCluterUnusedInf(sn))
            return usns
        
        elif keyword == "unused_node":
            con.deleteUnusedNode()
            return
        elif keyword == "duplicate_name":
            return con.check_duplicate_name()

        elif keyword == "need_hide":
            for _nt in ["clusterHandle","locator","follicle"]:
                con.type_visibility(_nt)
            return
        elif keyword == "fix_shapeName":
            con.fix_shapeName()
            return

        return
    
    def btn_fix(self,keyword):

        if keyword == "hide_joint":
            pg = editor.Progress()
            pg.win(" - Hide Joints - ")
            jots = mc.ls(type="joint")
            jotsNum = len(jots)
            pg.setMaxValue(jotsNum)
            for i, jot in enumerate(jots):
                pg.setStatus(jot)
                pg.setValue(i + 1)
                mc.setAttr(jot+".drawStyle",2)
            pg.endProgress()
            return
        
        elif keyword == "hide_locator":
            pg = editor.Progress()
            pg.win(" - Hide Locator - ")
            locs = mc.ls(type="locator")
            locsNum = len(locs)
            pg.setMaxValue(locsNum)
            for i, loc in enumerate(locs):
                pg.setStatus(loc)
                pg.setValue(i + 1)
                mc.hide(loc)
            pg.endProgress()
            return
        
        elif keyword == "hide_ikhandle":
            pg = editor.Progress()
            pg.win(" - Hide ikHandle - ")
            ikhs = mc.ls(type="ikHandle")
            ikhsNum = len(ikhs)
            pg.setMaxValue(ikhsNum)
            for i, ikh in enumerate(ikhs):
                pg.setStatus(ikh)
                pg.setValue(i + 1)
                mc.hide(ikh)
            pg.endProgress()
            return
        
        elif keyword == "delete_nodeEditorInfo":
            if mc.objExists("MayaNodeEditorSavedTabsInfo"):
                mc.delete("MayaNodeEditorSavedTabsInfo")
            return
        
        elif keyword == "hide_deformer":
            con.hideDeformer()
            return
        
        elif keyword == "clear_namespace":
            # nslist = con.getNamespace()
            # for ns in nslist:
            pg = editor.Progress()
            pg.win(" - NameSpace - ")
            con.clearNamespace(pg)
            return
        elif keyword == "delete_unusedItems":
            mel.eval('source "C:/Program Files/Autodesk/Maya2018/scripts/startup/cleanUpScene.mel"')
            items = [con.deleteUnusedNode,
                     con.deleteUnusedDeformers,
                     con.deleteUnusedDisplayLayers,
                     con.deleteUnusedGroupId,
                     con.deleteUnusedRenderLayers,
                     con.deleteUnusedSets,
                     con.deleteUnusedSkinInfs]
            pg = editor.Progress()
            pg.win(" - Clear Unused Items - ")
            pg.setMaxValue(len(items))
            for i,it in enumerate(items):
                pg.setStatus(it.__name__)
                pg.setValue(i + 1)
                it()
            pg.endProgress()
            return
        else:
            print "miss : %s"%keyword
        return

def showEditor():
    CheckEditor().win()


if __name__ == '__main__':
    pass